import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Card, Form, Input, Select, Button, message } from "antd";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { reqCategorys, reqProduct, reqAddOrUpdateProduct } from "../../api";
import PicturesWall from "./PicturesWall";
import RichTextEditor from "./RichTextEditor";
import qs from "qs";

const { Option } = Select;

const AddUpdate = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const [categorys, setCategorys] = useState([]);
  const [product, setProduct] = useState({});
  const pictureRef = useRef();
  const richEditorRef = useRef();

  useEffect(() => {
    const fetchProduct = async (id) => {
      const res = await reqProduct(id);
      if (res.status === 0) {
        setProduct(res.data);
        form.setFieldsValue(res.data);
      }
    };

    const query = qs.parse(location.search, { ignoreQueryPrefix: true });
    const productId = query.productId;
    if (productId) {
      fetchProduct(productId);
    }

    const fetchCategorys = async () => {
      const res = await reqCategorys();
      if (res.status === 0) {
        setCategorys(res.data);
      }
    };

    fetchCategorys();
  }, [location.search, form]);

  const handleSubmit = async (values) => {
    const { name, price, desc, categoryId } = values;
    const imgs = pictureRef.current.getImgs();
    const detail = richEditorRef.current.getDetail();
    const productData = { name, price, desc, categoryId, imgs, detail };
    if (product._id) {
      productData._id = product._id;
    }

    const res = await reqAddOrUpdateProduct(productData);

    if (res.status === 0) {
      message.success(`${product._id ? "修改" : "添加"}商品成功`);
      navigate("/products/product");
    } else {
      message.error(res.msg);
    }
  };

  const validatePrice = (_, value) => {
    if (value <= 0) {
      return Promise.reject(new Error("价格必须大于0"));
    }
    return Promise.resolve();
  };

  const title = (
    <span>
      <Button type="link" onClick={() => navigate(-1)}>
        <ArrowLeftOutlined />
      </Button>
      <span>{product._id ? "修改商品" : "添加商品"}</span>
    </span>
  );

  return (
    <Card title={title}>
      <Form form={form} onFinish={handleSubmit}>
        <Form.Item
          name="name"
          label="商品名称"
          rules={[{ required: true, message: "必须输入商品名称!" }]}
        >
          <Input placeholder="商品名称" />
        </Form.Item>
        <Form.Item
          name="desc"
          label="商品描述"
          rules={[{ required: true, message: "必须输入商品描述!" }]}
        >
          <Input placeholder="商品描述" />
        </Form.Item>
        <Form.Item
          name="price"
          label="商品价格"
          rules={[
            { required: true, message: "必须输入商品价格!" },
            { validator: validatePrice },
          ]}
        >
          <Input placeholder="商品价格" type="number" addonAfter="元" />
        </Form.Item>
        <Form.Item
          name="categoryId"
          label="商品分类"
          rules={[{ required: true, message: "必须选择商品分类!" }]}
        >
          <Select placeholder="请选择分类">
            {categorys.map((c) => (
              <Option key={c._id} value={c._id}>
                {c.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="商品图片">
          <PicturesWall ref={pictureRef} imgs={product.imgs} />
        </Form.Item>
        <Form.Item label="商品详情">
          <RichTextEditor ref={richEditorRef} detail={product.detail} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default AddUpdate;
